using System;
using JsonTestConsole;
using System.Collections.Generic;
using System.IO;
using System.Collections;
using System.Reflection;


namespace TodoSoft.Json
{
	internal class SerializeExpressionBuilder :ISerializeMethodBuilder
	{
		List<Action<object,TextWriter>> _actions;
		
		public SerializeExpressionBuilder ()
		{
			_actions = new List<Action<object, TextWriter>>();
		}
		
		#region ISerializeCodeGenerator implementation
		
	
		public void ConfigureConvertionMethod(Type type, Action<ISerializeMethodBuilder> action)
		{
			action(this);
		}
		
		public Action<object, TextWriter> GetConvertionMethod(Type type)
		{
			return (obj, textWriter) => {
				foreach(var act in _actions)
				{
					act(obj, textWriter);
				}
			};
		}
		

		public  List<Action<object,TextWriter>> GetActions()
		{
			return _actions;
		}
		
		
		public void EchoText (string text)
		{
			_actions.Add((obj, textWriter)=>{
				textWriter.Write(text);
			});
		}

		public void CallWriteLine (string text)
		{
			_actions.Add((obj, textWriter)=>{
				textWriter.WriteLine(text);
			});
		}

		public void WriteProperty(string name)
		{
			_actions.Add((obj, textWriter)=>{
			//method.WriteLine("if(!first)	textWriter.Write(\",\");	else first = false;");
				textWriter.Write(obj.GetType().GetProperty(name).GetValue(obj, null));
			});
		}
		
		public void EchoVar(short varIndex)
		{
			_actions.Add((obj, textWriter)=>{
				textWriter.Write(_vars[varIndex]);
			});
		}
		
		public void Foreach(string name, Action<ISerializeMethodBuilder, short> action)
		{
			/*var inner = new SerializeExpression();
			action(inner);
			
			var compiledActions = inner.GetActions();
			
			_actions.Add((obj, textWriter)=>{
				var val = (IEnumerable)obj.GetType().GetProperty(name).GetValue(obj, null);
				foreach(var item in val)
				{
					if(val != null)
					{
						foreach(var compiledAction in compiledActions)
						{
							compiledAction(obj, textWriter);
						}
					}
				}
			});*/
		}
		
		public void IfNotNull(string name, Action<ISerializeMethodBuilder> action)
		{
			/*
			var inner = new SerializeExpression();
			action(inner);
			
			var compiledActions = inner.GetActions();
			
			PropertyInfo pi = null;//!!!Надо запрашивать сразу тут.
			
			_actions.Add((obj, textWriter)=>{
				if(pi == null)
				{
					pi = obj.GetType().GetProperty(name);
				}
				object val = pi.GetValue(obj, null);
				if(val != null)
				{
					foreach(var compiledAction in compiledActions)
					{
						compiledAction(obj, textWriter);
					}
					
				}
			});
			*/
		}
		
		List<string> _vars = new List<string>();
		
		public short CreateStringVar(string initValue)
		{
			_vars.Add(initValue);
			return (short)(_vars.Count - 1);
		}
		
		public void SetVar(short varIndex, string varVal)
		{
			_vars[varIndex] = varVal;
		}
		
		public void CallConvertionMethod(string name)
		{
			
		}
		
		#endregion

	}
}